package handler

import (
	"developer-branch/api/request"
	"developer-branch/internal/consts"
	"developer-branch/internal/dao"
	"developer-branch/internal/model"
	"developer-branch/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	var user model.User
	if !dao.GetOneById(user.Id, &user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"date": nil,
		})
		return
	}

	if !dao.GetUserByMobile(req.Mobile) {
		u := model.User{
			Mobile:   req.Mobile,
			Password: req.Password,
		}
		if dao.Create(&u) {
			c.JSON(http.StatusOK, gin.H{
				"code": 10000,
				"msg":  "用户注册成功",
				"date": nil,
			})
		}
	}
	token, _ := pkg.NewJWT(consts.JWT_SELEST_KEY).CreateToken(pkg.CustomClaims{ID: user.Id})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"date": token,
	})

}
